<template>
  <div>
    <el-tabs v-model="consolidationIndex" @tab-click="handleSelectMenu">
      <el-tab-pane label="客户合并" name="0"></el-tab-pane>
      <el-tab-pane label="合并轨迹" name="1"></el-tab-pane>
    </el-tabs>
    <div v-if="+consolidationIndex === 0">
      <div class="wrap">
        <div class="title-header">添加待合并客户</div>
        <el-form :model="message">
          <el-row :gutter="10">
            <el-col :span="8">
              <el-form-item prop="sid" style="padding: 10px 0;">
                <el-input v-model="message.sid" placeholder="客户号" @blur="testSid(message.sid)" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="idType" style="padding: 10px 0;">
                <el-select v-model="message.idType" placeholder="证件类型" clearable style="width: 100%;">
                  <el-option v-for="item in idtypeOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="idCard" style="padding: 10px 0;">
                <el-input v-model="message.idCard" placeholder="证件号" @blur="testIdCard(message.idCard)" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item prop="phone" style="padding: 10px 0;">
                <el-input v-model="message.phone" placeholder="联系电话" @blur="testPhone(message.phone)" style="width: 100%;"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="16" style="text-align: right;">
              <el-button @click="handleQuery" type="primary">查询</el-button>
              <el-button @click="handleReset" type="info" plain>重置</el-button>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="addGridData" style="margin-top: 16px">
          <el-table-column property="sid" label="客户号" align="center" width="180"></el-table-column>
          <el-table-column property="name" label="姓名" align="center" width="120"></el-table-column>
          <el-table-column property="phone" label="联系电话" align="center" width="110"></el-table-column>
          <el-table-column property="idType" label="证件类型" align="center" width="120"></el-table-column>
          <el-table-column property="idCard" label="证件号码" align="center" width="160"></el-table-column>
          <el-table-column fixed="right" label="操作" width="60">
            <template slot-scope="scope">
              <el-button @click="handleClick(scope.row)" type="text" size="small">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
        <NormalPagination :currentPage="message.pageNum" :pageSize="message.pageSize" :total="addTotal" :pageSizeList="[5, 10, 20, 30]" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
      </div>
      <div class="wrap">
        <div class="title-header">待合并客户</div>
        <div style="display: flex ; justify-content: space-between">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm"  class="demo-ruleForm" style="display: flex ; justify-content: space-between">
            <el-form-item label="合并到" prop="sid" label-width="54px">
              <el-input disabled v-model="sid"></el-input>
            </el-form-item>
            <el-form-item label="合并原因" prop="mergeReason" label-width="74px">
              <el-input v-model="ruleForm.mergeReason"></el-input>
            </el-form-item>
          </el-form>
          <div>
            <el-button @click="confirm" type="primary" style="margin-top: 8px">确认合并</el-button>
          </div>
        </div>
        <el-table :data="waitGridData" fit style="margin-top: 16px">
          <el-table-column property="sid" label="客户号" align="center" :width="180"></el-table-column>
          <el-table-column property="name" label="姓名" align="center"></el-table-column>
          <el-table-column property="phone" label="联系电话" align="center"></el-table-column>
          <el-table-column property="idType" label="证件类型" align="center"></el-table-column>
          <el-table-column property="idCard" label="证件号码" align="center" :width="180"></el-table-column>
          <el-table-column fixed="right" label="操作" :width="60">
            <template slot-scope="scope">
              <el-button @click="waitHandleClick(scope.row)" type="text" size="small">移除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div v-if="+consolidationIndex === 1">
      <el-form :model="msg">
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item prop="beforeSid" style="padding: 10px 0;">
              <el-input v-model="msg.beforeSid" placeholder="合并前客户号" @blur="testSid(msg.beforeSid)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="afterSid" style="padding: 10px 0;">
              <el-input v-model="msg.afterSid" placeholder="合并后客户号" @blur="testSid(msg.afterSid)"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item style="padding: 10px 0;text-align: right;">
              <el-button @click="mergeSearch" type="primary">查询</el-button>
              <el-button @click="handleReset" type="info" plain>重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table :data="mergerGridData" style="margin-top: 10px;">
        <el-table-column property="name" label="姓名" align="center" :width="120"></el-table-column>
        <el-table-column property="sid" label="合并前客户号" align="center" :width="200"></el-table-column>
        <el-table-column property="parentSid" label="合并后客户号" align="center" :width="200"></el-table-column>
        <el-table-column property="mergeReason" label="合并原因" align="center"></el-table-column>
        <el-table-column property="mergeTime" label="合并日期" align="center" :width="140"></el-table-column>
        <el-table-column property="createBy" label="合并人" align="center" :width="140"></el-table-column>
        <el-table-column fixed="right" label="操作" :width="60" align="center">
          <template slot-scope="scope">
            <el-button @click="handleClickDetails(scope.row)" type="text" size="small">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <NormalPagination :currentPage="msg.pageNum" :pageSize="msg.pageSize" :total="gridTotal" :pageSizeList="[5, 10, 20, 30]" @handleSizeChange="handleSizeChange" @handleCurrentChange="handleCurrentChange"></NormalPagination>
    </div>
  </div>
</template>

<script>
import { validateIdentityCode, validateNum, validatePhone } from '@/utils/validate'
import { findCusMerge, findCusMergeTravel, unbinding, updateCusMerge } from '@/api/customer/customerManage'

export default {
  props: {
    sid: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      addGridData: [],
      message: {
        sid: '',
        idType: '',
        idCard: '',
        phone: '',
        pageNum: 1,
        pageSize: 5
      },
      idtypeOptions: [],
      addTotal: 0,
      ruleForm: {
        sid: this.sid,
        mergeReason: ''
      },
      reasonOptions: [],
      sidOptions: [],
      rules: {
        mergeReason: [
          { max: 20, message: '不能超过20个字符', trigger: 'blur' }
        ]
      },
      waitGridData: [],
      waitTotal: 50,
      waitPageNum: 1,
      waitPageSize: 5,
      msg: {
        beforeSid: '',
        afterSid: '',
        pageNum: 1,
        pageSize: 5
      },
      mergerGridData: [],
      gridTotal: 0,
      currentRowid: null,
    }
  },
  computed: {
    dialogTableVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    consolidationIndex: {
      get() {
        return this.id
      },
      set(val) {
        this.$emit('update:id', val)
      }
    }
  },
  created() {
    this.getDicts('id_type').then((res) => {
      if (res.code === 200) {
        this.idtypeOptions = res.data
      }
    })
  },
  mounted() {
    this.handleQuery()
    this.findCusMergeTravel()
  },
  methods: {
    handleSizeChange(val) {
      if(this.consolidationIndex == '0') {
        this.message.pageNum = 1;
        this.message.pageSize = val;
        this.handleQuery()
      } else {
        this.msg.pageNum = 1;
        this.msg.pageSize = val;
        this.mergeSearch()
      }
    },
    handleCurrentChange(val) {
      if(this.consolidationIndex == '0') {
        this.message.pageNum = val;
        this.handleQuery()
      } else {
        this.msg.pageNum = val;
        this.mergeSearch()
      }
    },
    closeDialog() {
      this.dialogTableVisible = false
    },
    handleSelectMenu() {
    },

    // 查询合并轨迹列表
    findCusMergeTravel() {
      let params = {
        id: this.sid || '',
        pageSize: this.msg.pageSize,
        pageNum: this.msg.pageNum,
        sid:'',
        lastsid:'',
      }
      findCusMergeTravel(params)
        .then((res) => {
          if (res.code === 200) {
            this.mergerGridData = res.rows
            this.gridTotal = res.total
          }
        })
        .catch(() => {
          console.log('error submit!!')
        })
    },
    mergeSearch() {
      //合并轨迹查询
      if (!this.testSid(this.msg.beforeSid) || !this.testSid(this.msg.afterSid)) return
      let params = {
        sid: this.msg.beforeSid,
        lastsid: this.msg.afterSid,
        pageSize: this.msg.pageSize,
        pageNum: this.msg.pageNum,
        id: this.sid
      }
      findCusMergeTravel(params)
        .then((res) => {
          if (res.code === 200) {
            this.mergerGridData = res.rows
            this.gridTotal = res.total
          }
        })
        .catch(() => {
          console.log('error submit!!')
        })
    },
    // 添加
    handleClick(value) {
      let flag = false;
      this.waitGridData.forEach(item => {
        if (item.sid === value.sid) flag = true;
      })
      if (flag) {
        this.$message.error('该条数据已添加！')
      } else {
        this.waitGridData.push(value)
      }
    },
    // 移除
    waitHandleClick(value) {
      this.waitGridData.splice(this.waitGridData.indexOf(value), 1)
    },
    // 合并轨迹
    handleClickDetails(row) {
      // 详情
      this.$router.push({
        path: "customerDetails",
        query: { sid: row.sid },
      });
      this.currentRowid = row.sid;
      this.$emit('getDetails' , row.sid)
      this.closeDialog()
    },
    handleClickFallback(row) {
      // 回退
      unbinding({ sid: row.sid }).then((res) => {
        if (res.code === 200) {
          this.$message.success('回退成功')
        }
      }).catch(() => {
        console.log('error submit!!')
      })
    },
    handleQuery() {
      if (!this.testIdCard(this.message.idCard)) return
      if (!this.testPhone(this.message.phone)) return
      if (!this.testSid(this.message.sid)) return
      const params = {
        ...this.message,
        id: this.sid
      }
      findCusMerge(params).then((res) => {
        if (res.code == 200) {
          this.addGridData = res.rows
          this.addGridData.forEach(element => {
            element.idType = this.selectDictLabel(this.idtypeOptions, element.idType)
          })
          this.addTotal = res.total
        }
      })
    },
    handleReset() {
      if (this.consolidationIndex == '0') {
        this.message = {
          idCard: '',
          phone: '',
          sid: '',
          pageNum: 1,
        };
        this.handleQuery()
      } else {
        this.msg = {
          beforeSid: '',
          afterSid: '',
          pageNum: 1
        };
        this.mergeSearch()
      }
    },
    confirm() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.waitGridData.length == 0) {
            this.$message.error('请添加要合并的客户')
            return
          }
          const arr = []
          this.waitGridData.forEach((item) => {
            arr.push(item.sid)
          })
          const params = {
            ...this.ruleForm,
            sids: arr
          }
          updateCusMerge(params).then((res) => {
            if (res.code == 200) {
              this.$message.success('合并成功')
              this.waitGridData = []
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    testIdCard(value) {
      try {
        if (value && !validateIdentityCode(value)) {
          throw new Error('请填写正确的身份证号')
        }
        return true
      } catch (error) {
        this.$message.error(error.message)
        return false
      }
    },
    testPhone(value) {
      try {
        if (value && !validatePhone(value)) {
          throw new Error('请填写正确的手机号')
        }
        return true
      } catch (error) {
        this.$message.error(error.message)
        return false
      }
    },
    testSid(value) {
      try {
        if (value && !validateNum(value)) {
          throw new Error('请填写正确的客户号')
        }
        return true
      } catch (error) {
        this.$message.error(error.message)
        return false
      }
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/styles/base.scss";
::v-deep .el-dialog__header {
  padding: 0 !important;
}
.wrap {
  @include titleWrap;
  padding: 10px;
}
</style>
